<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>NodeJS学习笔记(四)包 | 默默地向前端靠拢</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Node.js模块和包">
<meta name="keywords" content="NodeJs,JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="NodeJS学习笔记(四)包">
<meta property="og:url" content="http://yoursite.com/2016/04/28/node-study-3/index.html">
<meta property="og:site_name" content="默默地向前端靠拢">
<meta property="og:description" content="Node.js模块和包">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-02-13T08:52:43.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NodeJS学习笔记(四)包">
<meta name="twitter:description" content="Node.js模块和包">
  
    <link rel="alternative" href="/atom.xml" title="默默地向前端靠拢" type="application/atom+xml">
  
  
    <link rel="icon" href="/img/head.jpg">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/img/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">心情</a></h1>
		</hgroup>

		
		<p class="header-subtitle">你所浪费的今天，是昨天死去的人奢望的明天；你所厌恶的现在，是未来的你回不去的曾经。</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
						<div class="icon-wrap icon-me hide" data-idx="3">
							<div class="user"></div>
							<div class="shoulder"></div>
						</div>
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
						<li>关于我</li>
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/">主页</a></li>
				        
							<li><a href="/archives">所有文章</a></li>
				        
							<li><a href="/categories/随笔">随笔总结</a></li>
				        
							<li><a href="/categories/笔记">学习笔记</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
								<a class="github" target="_blank" href="http://springxiege.gitbub.io" title="github">github</a>
					        
								<a class="weibo" target="_blank" href="http://weibo.com/springxiegel" title="weibo">weibo</a>
					        
								<a class="mail" target="_blank" href="mailto://springxiege@sina.cn" title="mail">mail</a>
					        
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						<a href="/tags/Git/" style="font-size: 10px;">Git</a> <a href="/tags/HTML5/" style="font-size: 10px;">HTML5</a> <a href="/tags/JS/" style="font-size: 20px;">JS</a> <a href="/tags/JavaScript/" style="font-size: 13.33px;">JavaScript</a> <a href="/tags/Node/" style="font-size: 10px;">Node</a> <a href="/tags/NodeJS/" style="font-size: 16.67px;">NodeJS</a> <a href="/tags/NodeJs/" style="font-size: 10px;">NodeJs</a> <a href="/tags/React-js/" style="font-size: 13.33px;">React.js</a> <a href="/tags/hexo/" style="font-size: 10px;">hexo</a>
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.52cik.com/">乱码大大的博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://webcaiqingchong.github.io/">菜青虫的博客</a>
			        
			        </div>
				</section>
				

				
				
				<section class="switch-part switch-part4">
				
					<div id="js-aboutme">我是心情，我是一名前端工作者，目前靠Coding讨生活！平时喜欢玩三国杀，听音乐，运动也喜欢，只是现在运动项目做得少了。</div>
				</section>
				
			</div>
		</div>
	</header>				
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">心情</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
			
				<img lazy-src="/img/head.jpg" class="js-avatar">
			
			</div>
			<hgroup>
			  <h1 class="header-author">心情</h1>
			</hgroup>
			
			<p class="header-subtitle">你所浪费的今天，是昨天死去的人奢望的明天；你所厌恶的现在，是未来的你回不去的曾经。</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
					<li><a href="/categories/随笔">随笔总结</a></li>
		        
					<li><a href="/categories/笔记">学习笔记</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="http://springxiege.gitbub.io" title="github">github</a>
			        
						<a class="weibo" target="_blank" href="http://weibo.com/springxiegel" title="weibo">weibo</a>
			        
						<a class="mail" target="_blank" href="mailto://springxiege@sina.cn" title="mail">mail</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap"><article id="post-node-study-3" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2016/04/28/node-study-3/" class="article-date">
  	<time datetime="2016-04-28T13:52:15.000Z" itemprop="datePublished">2016-04-28</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      NodeJS学习笔记(四)包
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
	<div class="article-tag tagcloud">
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JS/">JS</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/NodeJS/">NodeJS</a></li></ul>
	</div>

        
	<div class="article-category tagcloud">
	<a class="article-category-link" href="/categories/笔记/">笔记</a>
	</div>


        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>对于Node.js的包的理解，是非常抽象的。对于这个，我刚开始接触的时候，也是一头雾水，那先来看看Node.js里面是怎么定义包的。<br>包是模块基础上更深一步的抽象，Node.js的包类似C/C++的函数库或者Java/.Net的类库。它的将某个独立的功能封装起来，用于发布、更新、依赖管理和版本控制。Node.js根据CommonJS规范实现了包机制，开发了npm来解决包的发布和获取需求。<br><a id="more"></a></p>
<blockquote>
<p>Node.js的包是一个目录，其中包含一个JSON格式的包说明文件pagkage.json。严格符合CommonJS规范的包应该具备以下特征：</p>
</blockquote>
<ul>
<li>package.json必须在包的顶层目录下;</li>
<li>二进制文件应该在bin目录下;</li>
<li>JavaScript代码应该在lib目录下;</li>
<li>文档应该在doc目录下;</li>
<li>单元测试应该在test目录下。</li>
</ul>
<p>Node.js对包的要求并没有这么严格，只要顶层目录下有package.json，并符合一些规范即可。当然为了提高兼容性，还是建议在制作包的时候，严格遵守CommonJS规范。</p>
<h2 id="作为文件夹的模块"><a href="#作为文件夹的模块" class="headerlink" title="作为文件夹的模块"></a>作为文件夹的模块</h2><p>模块与文件是一一对应的。文件不仅可以是JavaScript代码或二进制代码，还可以是一个文件夹。最简单的包，就是一个作为文件夹的模块。下面我们举个例子，创建一个somepackage的文件夹，然后在其中创建index.js文件，内容如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// somepackage/index.js</span></div><div class="line">exports.hello = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">'Hello'</span>);</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>然后在somepackage文件夹之外创建一个getpackage.js文件，内容如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// getpackage.js</span></div><div class="line"><span class="keyword">var</span> somepackage = <span class="built_in">require</span>(<span class="string">'./somepackage'</span>);</div><div class="line">somepackage.hello();</div></pre></td></tr></table></figure></p>
<p>运行node getpackage.js,控制台将输出结果：hello.<br>我们使用这种方法可以把文件夹封装为一个模块，即所谓的包。包通常是一些模块的集合，在模块的基础上提供了更高层的抽象，相当于提供了一些固定接口的函数库。通过定制package.json,我们可以创建更复杂、更完善、更符合规范的包用于发布。</p>
<blockquote>
<p>细说package.json</p>
</blockquote>
<p>在前面例子中的 somepackage 文件夹下，我们创建一个叫做 package.json 的文件，内容如下所示：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"main"</span>:<span class="string">"./lib/interface.js"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>然后将index.js重命名为interface.js并放入lib子文件夹下，然后我将interface.js里面的输出内容改为hello,mood!。以同样的方式再次调用这个包，依然可以正常使用。终端输出结果为：hello,mood!</p>
<blockquote>
<p>Node.js 在调用某个包时，会首先检查包中 package.json 文件的 main 字段，将其作为包的接口模块，如果 package.json 或 main 字段不存在，会尝试寻找 index.js 或 index.node 作为包的接口。</p>
</blockquote>
<p>package.json 是 CommonJS 规定的用来描述包的文件，完全符合规范的 package.json 文件应该含有以下字段:</p>
<ul>
<li>name:包的名称，必须是唯一的，由小写英文字母、数字和下划线组成，不能包含空格。</li>
<li>description：包的简要说明。</li>
<li>version：符合语义化版本识别规范的版本字符串。</li>
<li>keywords：关键字数组，通常用于搜索。</li>
<li>maintainers：维护者数组，每个元素要包含 name、 email （可选）、 web （可选）字段。</li>
<li>contributors：贡献者数组，格式与maintainers相同。包的作者应该是贡献者数组的第一个元素。</li>
<li>bugs:提交bug的地址，可以是网址或者电子邮件地址。</li>
<li>licenses：许可证数组，每个元素要包含 type （许可证的名称）和 url （链接到许可证文本的地址）字段。</li>
<li>repositories：仓库托管地址数组，每个元素要包含 type（仓库的类型，如 git ）、url （仓库的地址）和 path （相对于仓库的路径，可选）字段。</li>
<li>dependencies：包的依赖，一个关联数组，由包名称和版本号组成。</li>
</ul>
<p>现在，给出一个完全符合CommonJS规范的package.json示例：<br><figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"name"</span>:<span class="string">"mypackage"</span>,</div><div class="line">    <span class="attr">"description"</span>:<span class="string">"Sample package for CommonJS. This package demonstrates the required elements of a CommonJS package."</span>,</div><div class="line">    <span class="attr">"version"</span>:<span class="string">"0.7.0"</span>,</div><div class="line">    <span class="attr">"keywords"</span>:[</div><div class="line">        <span class="string">"package"</span>,</div><div class="line">        <span class="string">"example"</span></div><div class="line">    ],</div><div class="line">    <span class="attr">"maintainers"</span>:[</div><div class="line">        &#123;</div><div class="line">            <span class="attr">"name"</span>:<span class="string">"Springxiegel"</span>,</div><div class="line">            <span class="attr">"email"</span>:<span class="string">"springxiege@sina.cn"</span></div><div class="line">        &#125;</div><div class="line">    ],</div><div class="line">    <span class="attr">"contributors"</span>:[</div><div class="line">        &#123;</div><div class="line">            <span class="attr">"name"</span>:<span class="string">"XieGe"</span>,</div><div class="line">            <span class="attr">"web"</span>:<span class="string">"http://springxiege.github.io"</span></div><div class="line">        &#125;</div><div class="line">    ],</div><div class="line">    <span class="attr">"bugs"</span>:&#123;</div><div class="line">        <span class="attr">"mail"</span>:<span class="string">"1953744343@qq.com"</span>,</div><div class="line">        <span class="attr">"web"</span>:<span class="string">"http://springxiege.github.io"</span></div><div class="line">    &#125;,</div><div class="line">    <span class="attr">"licenses"</span>:[</div><div class="line">        &#123;</div><div class="line">            <span class="attr">"type"</span>:<span class="string">"GPLv2"</span>,</div><div class="line">            <span class="attr">"url"</span>:<span class="string">"http://springxiege.github.io"</span></div><div class="line">        &#125;</div><div class="line">    ],</div><div class="line">    <span class="attr">"repositories"</span>:[</div><div class="line">        &#123;</div><div class="line">            <span class="attr">"type"</span>:<span class="string">"get"</span>,</div><div class="line">            <span class="attr">"url"</span>:<span class="string">"http://springxiege.github.io"</span></div><div class="line">        &#125;</div><div class="line">    ],</div><div class="line">    <span class="attr">"dependencies"</span>:[</div><div class="line">        &#123;</div><div class="line">            <span class="attr">"webkit"</span>:<span class="string">"1.2"</span>,</div><div class="line">            <span class="attr">"ssl"</span>:&#123;</div><div class="line">                <span class="attr">"gnutls"</span>:[<span class="string">"1.0"</span>,<span class="string">"2.0"</span>],</div><div class="line">                <span class="attr">"openssl"</span>:<span class="string">"0.9.8"</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    ]</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="？疑问：如果将package-json里面的main字段改成sub字段，但是我又想获取sub字段的模块，该怎么获取呢？"><a href="#？疑问：如果将package-json里面的main字段改成sub字段，但是我又想获取sub字段的模块，该怎么获取呢？" class="headerlink" title="？疑问：如果将package.json里面的main字段改成sub字段，但是我又想获取sub字段的模块，该怎么获取呢？"></a>？疑问：如果将package.json里面的main字段改成sub字段，但是我又想获取sub字段的模块，该怎么获取呢？</h2><p>对于这个疑问，我也是一头雾水弄不明白，看来只能搞搞清楚后再作解答了。</p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2016/04/29/node-study-4/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption"><</strong>
      <div class="article-nav-title">
        
          NodeJS学习笔记(五)调试
        
      </div>
    </a>
  
  
    <a href="/2016/04/27/node-study-2/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">NodeJS学习笔记(三)模块</div>
      <strong class="article-nav-caption">></strong>
    </a>
  
</nav>

  
</article>


<div class="share share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">分享到: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
    <a class="jiathis_button_twitter"></a>
    <a class="jiathis_button_plus"></a> 
    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="node-study-3" data-title="NodeJS学习笔记(四)包" data-url="http://yoursite.com/2016/04/28/node-study-3/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"true"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>




</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2017 心情
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>






<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  </div>
</body>
</html>